﻿using Aliphant.Mvvm.XEvent.Interface;
using Aliphant.Mvvm.XEvent.Ioc;

using CommonLibrary.Helper;
using CommonLibrary.Pools;

using CuteWallpaperDemo.Managers;
using CuteWallpaperDemo.Models;
using CuteWallpaperDemo.UI;
using CuteWallpaperDemo.Views;

using DataModel.Contants;

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace CuteWallpaperDemo
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {
        private Mutex? _mutex;

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        private static extern bool IsIconic(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        private static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);


        private const int SW_RESTORE = 9;

        protected override void OnStartup(StartupEventArgs e)
        {
            ConfigManager.Instance.Init();
            AppDefines.OssConfig = ConfigManager.Instance.Settings.OssConfig;
            DomainHelper.WallpaperPath = ConfigManager.Instance.Settings.WallpaperHubPath;

            //唯一进程实例
            _mutex = new Mutex(true, "Cute_Wallpaper", out bool running);
            if (!running)
            {
                ActivateOtherInstance();
                //MessageBox.Show("程序已运行");
                AppConst.PupExitAlert = false;
                Current.Shutdown();
                return;
            }

            base.OnStartup(e);
            NotifyManager.Instance.Register<AlertWindow>("alert");

            switch (AppDefines.GetSourceMode)
            {
                case "pic":
                    InitPicSourceWindow();
                    break;
                case "bmp":
                default:
                    InitBmpSourceWindow();
                    break;
            }

            NotifyHelper.Init();
            Current.MainWindow.Show();

            ThreadPoolFactory.AdvancedPoolHandler.Start(12);
        }

        private static void InitBmpSourceWindow()
        {
            //主页版本
            if (AppDefines.GetMainWindowVersion == "2")
            {
                Current.MainWindow = new Views.MainWindow();
            }
            else
            {
                Current.MainWindow = new Views.NewMainWindow();
            }
        }

        private static void InitPicSourceWindow()
        {
            DomainHelper.WallpaperPath = ConfigManager.Instance.Settings.WallpaperHubPathNew;
            Current.MainWindow = new Views.NewSourceMainWindow();
        }


        /// <summary>
        /// 激活进程窗口
        /// </summary>
        private void ActivateOtherInstance()
        {
            // 获取当前进程的名称
            string currentProcessName = Process.GetCurrentProcess().ProcessName;

            // 查找已运行的实例
            Process[] processes = Process.GetProcessesByName(currentProcessName);
            foreach (var process in processes)
            {
                if (process.Id != Process.GetCurrentProcess().Id)
                {
                    IntPtr hWnd = process.MainWindowHandle;

                    // 如果窗口最小化，则恢复
                    if (IsIconic(hWnd))
                    {
                        ShowWindowAsync(hWnd, SW_RESTORE);
                    }

                    // 将窗口前置
                    SetForegroundWindow(hWnd);
                    break;
                }
            }
        }

        protected override void OnExit(ExitEventArgs e)
        {
            ConfigManager.Instance.Save();
            base.OnExit(e);
        }

        public override void RegisterTypes(IXContainer container)
        {
            container.RegisterNavigation<MainPictureList>("mainPictureList");
            container.RegisterNavigation<PicturePreview>("picturePreview");
            container.RegisterNavigation<PlayControl>("playControl");
            container.RegisterNavigation<ToolBar>("toolsControl");
        }
    }
}
